<template>
    <div id="hzxTable" @scroll="handleScroll" ref="table">
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";

const table = ref<HTMLAreaElement | null>(null);
const items = ref<number[]>(Array.from({ length: 100 }, (_, i) => i));
const data = ref<number[]>([]);
const itemHeight = ref(30);
const visibleCount = ref(10);
const scrollTop = ref(0);
const startIndex = ref(0)

onMounted(() => {
    if (table.value) {
        handleScroll()
        const throttledHandleScroll = throttle(handleScroll, 100);
        table.value.addEventListener('scroll', throttledHandleScroll);
       
    }
});
const handleScroll = () => {
    const scrollTop = table.value!.scrollTop;
    const visibleStart = Math.max(0, Math.floor(scrollTop / itemHeight.value) - 2);
    const visibleEnd = Math.min(
        items.value.length,
        visibleStart + Math.ceil(700 / itemHeight.value) + 2 
    );
    startIndex.value = visibleStart;
    data.value = items.value.slice(visibleStart, visibleEnd);
    renderVisibleData();
}
const throttle = (func, limit)=> {
            let inThrottle;
            return function () {
                const args = arguments;
                const context = this;
                if (!inThrottle) {
                    func.apply(context, args);
                    inThrottle = true;
                    setTimeout(() => (inThrottle = false), limit);
                }
            };
        }



const renderVisibleData = () => {
    if (table.value) {
        const fragment = document.createDocumentFragment();

        const existingItems = table.value.querySelectorAll('.item');
        console.log("len", existingItems);
        if (existingItems.length) {
            existingItems.forEach((item, index) => {
                const htmlElement = item as HTMLElement;
                htmlElement.style.top = (startIndex.value + index) * itemHeight.value + "px";
                htmlElement.textContent = `数据-${data.value[index]}`;
            });
            return 
        }

        // existingItems.forEach(item => {
        //     table.value!.removeChild(item);
        // });

        data.value.forEach((item, index) => {
            const div = document.createElement("div");
            div.className = "item";
            div.style.top = (startIndex.value + index) * itemHeight.value + "px";
            div.textContent = `数据-${item}`;
            fragment.appendChild(div);
        });
        table.value.appendChild(fragment);
    }
}
</script>

<style scoped lang="scss">
#hzxTable {
    width: 500px;
    height: 700px;
    margin: 30px;
    overflow: auto;
    position: relative;
    border: 1px solid #ccc;



}

</style>
